<?php
declare (strict_types=1);

namespace addons\V2\admin\model;

use app\common\model\Base;
use think\facade\Cache;

class ProductCart extends Base
{
    protected $name = 'addons_mall_product_cart';


    public function product()
    {
        return $this->hasOne(Product::class, 'id', 'pid')
            ->field('id,title,icon,price,cate_1,icon,stock,status,freight,vip_price');
    }


    public function spec()
    {
        return $this->hasOne(ProductSpecValue::class, 'id', 'spec_value_id')
            ->field('id,vip_price,icon,stock');
    }


    public static function getSettled($user, $id): array
    {
        try {
            if (empty($id)) {
                return ['code' => -1, 'msg' => '请选择要结算的商品'];
            }
            $freightTotal = 0;
            $total = 0;
            $productAll = [];
            $cate_1 = [];
            $product = parent::with(['product', 'spec'])
                ->whereIn('id', $id)
                ->where('uid', $user->id)
                ->field('id,cate_1,pid,num,spec_value_id,sku_id,sku_name')
                ->select();
            if ($product->isEmpty()) {
                return ['code' => -1, 'msg' => '请选择要结算的商品'];
            }
            foreach ($product as $vo) {
                if ($vo->product->status != 1) {
                    return ['code' => -1, 'msg' => '商品《' . $vo->product->title . '》已下架'];
                }
                if ($vo->spec_value_id) {
                    $sku_name = SpecItem::getSpecItemName($vo->sku_id);
                    if ($vo->num > $vo->spec->stock) {
                        return ['code' => -1, 'msg' => '商品《' . $vo->product->title . '/ ' . $sku_name . '》库存不足'];
                    }
                } else {
                    if ($vo->num > $vo->product->stock) {
                        return ['code' => -1, 'msg' => '商品《' . $vo->product->title . '》库存不足'];
                    }
                }
                $productAll[] = [
                    'pid'           => $vo->pid,
                    'title'         => $vo->product->title,
                    'icon'          => $vo->product->icon,
                    'spec_value_id' => $vo->spec_value_id,
                    'vip_price'     => $vo->spec ? $vo->spec->vip_price : $vo->product->vip_price,
                    'sku_name'      => $vo->sku_name ?: '',
                    'num'           => $vo->num,
                    'cate_1'        => $vo->product->cate_1
                ];
                $cate_1[] = $vo->cate_1;
                $freightTotal += $vo->product->freight * $vo->num;
                $total += $vo->spec ? $vo->spec->vip_price : $vo->product->vip_price * $vo->num;
            }

            $list = [
                'product'      => $productAll,
                'total'        => $total,
                'freightTotal' => $freightTotal,
                'realTotal'    => $total + $freightTotal,
                'cate_1'       => $cate_1,
            ];

            return ['code' => 1, 'msg' => 'success', 'data' => $list];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    public static function getMyCart($user): array
    {
        try {
            $msg = 'success';
            $product = parent::with(['product', 'spec'])
                ->where('uid', $user->id)
                ->field('id,cate_1,pid,num,spec_value_id,sku_name,sku_id,status')
                ->select();
            $children = [];
            foreach ($product as $vo) {
                $children[] = [
                    'id'            => $vo->id,
                    'pid'           => $vo->pid,
                    'title'         => $vo->product->title,
                    'icon'          => isset($vo->spec) ? $vo->spec->icon : $vo->product->icon,
                    'spec_value_id' => $vo->spec_value_id,
                    'sku_id'        => $vo->sku_id,
                    'sku_name'      => $vo->sku_name,
                    'vip_price'     => isset($vo->spec) ? $vo->spec->vip_price : $vo->product->vip_price,
                    'num'           => $vo->num,
                    'stock'         => isset($vo->spec) ? $vo->spec->stock : $vo->product->stock,
                    'status'        => $vo->status
                ];
            }
            return ['code' => 1, 'msg' => $msg, 'data' => $children];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function add($param, $user): array
    {
        try {

            $product = Product::where(['id' => $param['pid'], 'status' => 1])
                ->field('id,cate_1,spec_open,stock')->find();
            if (empty($product)) {
                return ['code' => -1, 'msg' => '商品不存在或已下架'];
            }
            $num = ProductCart::where(['cate_1'=>$product->cate_1])->count();
            if ($num) {
                return ['code' => -1, 'msg' => '不同专区无法同时放入购物车'];
            }
            if (!$param['num'] || $param['num'] <= 0) {
                return ['code' => -1, 'msg' => '数量错误'];
            }
            if ($param['num'] > $product->stock) {
                return ['code' => -1, 'msg' => '库存不足'];
            }
            $map['uid'] = $user->id;
            $map['cate_1'] = $product->cate_1;
            $map['pid'] = $product->id;
            if ($product->spec_open) {
                $specValue = ProductSpecValue::where('id', $param['spec_value_id'])->find();
                if (empty($specValue)) {
                    return ['code' => -1, 'msg' => '未查询到相关规格'];
                }
                $map['spec_value_id'] = $specValue->id;
                $map['sku_id'] = $specValue->sku_id;
                $map['sku_name'] = SpecItem::getSpecItemName($specValue->sku_id);
            }

            $cart = parent::where($map)->find();
            if ($cart) {
                $cart->num = $cart->num + $param['num'];
                $cart->save();
            } else {
                $map['num'] = $param['num'];
                parent::create($map);
            }
            return ['code' => 1, 'msg' => '加入购物车成功'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function edit($param, $user): array
    {
        try {
            $msg = 'success';
            switch ($param['type']) {
                case 1://加
                    $info = parent::where('id', $param['id'])->field('id,num,pid')->find();
                    if ($info->num >= $info->product->stock) {
                        return ['code' => -1, 'msg' => '库存不足'];
                    }
                    $info->num = $info->num + 1;
                    $info->save();
                    break;
                case 2://减
                    $info = parent::where('id', $param['id'])->field('id,num')->find();
                    if ($info->num <= 1) {
                        return ['code' => -1, 'msg' => '数量至少为1'];
                    }
                    $info->num = $info->num - 1;
                    $info->save();
                    break;
                case 3://删
                    parent::whereIn('id', $param['id'])->delete();
                    $msg = '已删除';
                    break;
                default:
                    return ['code' => -1, 'msg' => '加载失败'];
            }
            return ['code' => 1, 'msg' => $msg];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function submit($param, $user): array
    {
        try {
            $all = [];
            foreach ($param['cart_id'] as $k => $v) {
                $all[$k] = parent::where('id', $v)->field('pid,num,cate_1')->find()->toArray();
            }
            Cache::set('tsOrder_' . $user->id, json_encode($all));
            Cache::set('tsOrderCartIds_' . $user->id, json_encode($param['cart_id']));

            return ['code' => 1, 'msg' => 'success', 'url' => url('order/index')->build()];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function clearCart($uid)
    {
        Cache::set('tsOrder_' . $uid, null);
        $ids = Cache::get('tsOrderCartIds_' . $uid);
        if (!empty($ids)) {
            parent::destroy(json_decode($ids, true));
        }
    }

}
